﻿using Autofac.Core;
using DFGK.WMS.Common.Result;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models;
using DFGK_WMS.WebAPI.Controllers.Result;
using DFGK_WMS.WebAPI.Tools;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.XWPF.UserModel;
using SqlSugar;
using System.Net.Mime;
using System.Security.Claims;
using System.Xml.Linq;

namespace DFGK_WMS.WebAPI.Controllers.盘点管理
{
    /// <summary>
    /// 盘点单管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TStocktakingOrderController : ControllerBase
    {
        private readonly ILogRepository logRepository;
        public TStocktakingOrderController(ITStocktakingOrderRepository stoService,ILogRepository logRepository)
        {
            StoService = stoService;
            this.logRepository = logRepository;
        }
      
        public ITStocktakingOrderRepository StoService { get; }
        MemoryStream ProcessExcelData()
        {
            //模块从表中读取的数据
            List<TStocktakingOrder> list = new List<TStocktakingOrder>();
            list = StoService.GetStockingExcel();
            // 已经读取出了正确的数据后
            //创建Excel对象把数据赋值到对象中
            IWorkbook workbook = new XSSFWorkbook(); // Excel对象
            ISheet sheet1 = workbook.CreateSheet("盘点单号");  // 创建Excel中的表对象
            //表头
            IRow row0 = sheet1.CreateRow(0);  // 在sheet1表格中创建第0行
            row0.CreateCell(0).SetCellValue("名称"); // 在sheet1表格中第0行创建第0列，并且在给这个单元格赋值
            row0.CreateCell(1).SetCellValue("库房");
            row0.CreateCell(2).SetCellValue("库区");
            row0.CreateCell(3).SetCellValue("物料名称");
            row0.CreateCell(4).SetCellValue("单据类型");
            row0.CreateCell(5).SetCellValue("盘点类型");
            row0.CreateCell(6).SetCellValue("盘点方法");
            row0.CreateCell(7).SetCellValue("批次号");
            row0.CreateCell(8).SetCellValue("创建人");
            row0.CreateCell(9).SetCellValue("创建时间");
            var rowIndex = 1;
            foreach (var item in list)
            {
                IRow row = sheet1.CreateRow(rowIndex);
                row.CreateCell(0).SetCellValue(item.Name);
                row.CreateCell(1).SetCellValue(item.WarehouseName);
                row.CreateCell(2).SetCellValue(item.AreaName);
                row.CreateCell(3).SetCellValue(item.MaterialName);
                row.CreateCell(4).SetCellValue(string.Empty);
                row.CreateCell(5).SetCellValue("未知");
                row.CreateCell(6).SetCellValue("");
                row.CreateCell(7).SetCellValue(item.BatchNo);
                row.CreateCell(8).SetCellValue(item.CreateUserName);
                row.CreateCell(9).SetCellValue(item.CreateDate.ToString());
                rowIndex++;
            }
            MemoryStream ms = new MemoryStream();
            workbook.Write(ms);

            return ms;
        }
        /// <summary>
        /// 下载盘点单号
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public FileContentResult DownStocktaking()
        {
            MemoryStream ms = ProcessExcelData();
            byte[] fileBytes = ms.ToArray();
            return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, "盘点单号.xlsx"); //关键语句
        }

        /// <summary>
        /// 新增盘点单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddStocktakingOrder(TStocktakingOrderDto dto)
        {
            string message = "";
            bool isko = StoService.AddStocktakingOrder(dto,out message);
            if (isko)
            {
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 4;
                logg.ModuleName = "盘点管理";
                logg.UserName = uname;
                logg.RealName = runame;
                logg.UserId = uid;
                logg.Description = uname + "创建了盘点单" + dto.OrderSn;
                //获取前端IP地址
                logg.Ipaddress = ip;

                logRepository.AddTLod(logg);
                return Ok(BaseResult.Result(true, "添加成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "添加失败！"+message, "500"));
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPut]
        public ActionResult UpdateStocktakingOrder(TStocktakingOrderDto dto)
        {
            if(dto.Id<=0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            string message = "";
            bool isko = StoService.UpdateStocktakingOrder(dto,out message);
            if (isko)
            {
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 6;
                logg.ModuleName = "盘点管理";
                logg.UserName = uname;
                logg.RealName = runame;
                logg.UserId = uid;
                logg.Description = uname + "修改了盘点单" + dto.OrderSn;
                //获取前端IP地址
                logg.Ipaddress = ip;

                logRepository.AddTLod(logg);
                return Ok(BaseResult.Result(true, "修改成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "修改失败！"+message, "500"));
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpDelete]
        public ActionResult DelStocktakingOrder(int ids)
        {
            if(ids<=0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            bool isko = StoService.DelStocktakingOrder(ids);
            if (isko)
            {
                return Ok(BaseResult.Result(true, "删除成功", "200"));
            }
            return Ok(BaseResult.Result(false, "删除失败", "500"));
        }
        /// <summary>
        ///盘点单显示
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="wid"></param>
        /// <param name="aid"></param>
        /// <param name="name"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTstockordechaxun(DateTime? startTime, DateTime? endTime, int? wid, int? aid, string? name, int pageIndex = 1, int pageSize = 10)
        {
            int totalCount;
            string meessage;
            var list = StoService.GetTstockordechaxun(startTime, endTime, wid, aid, name, pageIndex, pageSize, out totalCount);
            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GetStocktakingOrder(int ids)
        {
            if(ids<=0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var car = StoService.GetStocktakingOrder(ids);
            return Ok(BaseResult.Result(car, "查询成功", "200"));
        }

        /// <summary>
        /// 根据库房库区获取库存
        /// </summary>
        /// <param name="wid"></param>
        /// <param name="aid"></param>
        /// <param name="name"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetWhArList(int? wid=0,int? aid=0,string? name="",string?cangkuname="" ,int pageIndex=1,int pageSize=20, int totalCount=0)
        {
           
            if(pageIndex<=0 || pageSize<=0)
            {
                return Ok(BaseResult.Result("400", "分页条件有误！"));
            }

            var list = StoService.GetWhArList(wid, aid,name,cangkuname, pageIndex, pageSize, out totalCount);

            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }

        /// <summary>
        /// 枚举盘点单据类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetEmStocktakeBillType()
        {
            var list = BaseEnum.GetCodeRulesList<EmStocktakeBillType>();

            return Ok(list);
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult UpdTStocktakingOrderState(ReceivingOrderDetailDto m)
        {
            if(m.Id<=0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            string message;
            bool IsOK = StoService.UpdTStocktakingOrderState(m,out message);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "修改成功！", "200"));
            }
            return Ok(BaseResult.Result(false, message, "500"));
        }
        /// <summary>
        /// 根据盘点计划单号查询盘点单号的数据
        /// </summary>
        /// <param name="ordersn"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTstockordernums(string? ordersn)
        {
            int totalt;
            ApiItemsResult itemsresult=new ApiItemsResult();
            ApiBaseResult apiBaseResult = new ApiBaseResult();
            var list = StoService.GetTstockordernums(ordersn);
           
            if (list!=null)
            {
               // itemsresult.code = "200";
               // itemsresult.message = "查询成功";
               // itemsresult.data= list;
               // itemsresult.count = totalt;
                return Ok(BaseResult.Result(list,"200"));
            }
            itemsresult.code = "500";
            itemsresult.message = "查询失败,没有盘点单号";
            itemsresult.data = list;
            return Ok(itemsresult);
        }
        /// <summary>
        /// 修改盘点单的状态
        /// </summary>
        /// <param name="Ordernum"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult GetPcState(string Ordernum)
        {
            string message;
            ApiItemsResult itemsresult = new ApiItemsResult();
            bool pandian= StoService.UpdateStatetai(Ordernum,out message);
            if (pandian)
            {
                itemsresult.code = "200";
                itemsresult.message = "已查询";
                itemsresult.data = pandian;;
                return Ok(BaseResult.Result(true, "200"));
            }
            return Ok(BaseResult.Result(false, "500"));
        }
        //[HttpGet("ExportToExcel")]
        //public FileContentResult ExportToExcel(DateTime? startTime, DateTime? endTime, int? billType, int? houseid, string? name)
        //{
        //    var list = StoService.GetOuHouseToExcel(startTime, endTime, billType, houseid, name, 1, int.MaxValue, out var totalCount);
        //    var dic = new Dictionary<string, string>()
        //    {
        //        {"OrdeSn","单号" },
        //        {"MaterialName","物料描述" },
        //        {"MaterialCode","物料代码" },
        //        {"isChuku", "状态"},
        //        {"BatchNo","批次" },
        //        {"SmallBatchNo","详细批次" },
        //        {"CellName","仓位名称" },
        //        {"OutQty","出库数量" },
        //        {"InvCount","库存剩余数量" },
        //        {"keChuCount","可出库数量" },
        //        {"PalletBarcode","托盘条码" },
        //        {"ProductionTime","生产时间" },
        //        {"CarCode","车牌号" }
        //    };
        //    var exList = list.Select(s => new {
        //        s.OrdeSn,
        //        s.MaterialName,
        //        s.MaterialCode,
        //        isChuku = s.IsPicking.GetValueOrDefault() ? "已出库" : "未出库",
        //        s.BatchNo,
        //        s.SmallBatchNo,
        //        s.CellName,
        //        s.CarCode,
        //        InvCount = (int)s.InvCount.GetValueOrDefault(),
        //        OutQty = (int)s.OutQty.GetValueOrDefault(),
        //        keChuCount = (int)s.keChuCount.GetValueOrDefault(),
        //        s.PalletBarcode,
        //        s.ProductionTime
        //    }).ToList();
        //    var fileBytes = Utils.ExportToExcel(exList, dic);
        //    return File(fileBytes, MediaTypeNames.Application.Octet, "出库管理.xlsx");
        //}



    }
}
